<template>
    <div class="set_dialog">
        <el-dialog v-model="state.show" title="设置商品佣金" width="710px" @close="onClose">
            <el-form ref="formRef" :model="form" :show-message="false" v-loading="state.loading" label-width="auto">
                <el-form-item label="佣金比例">
                    <el-radio-group v-model="form.type">
                        <el-radio :label="1">默认佣金</el-radio>
                        <el-radio :label="2">自定义佣金</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label=" ">
                    <el-table :data="form.type == 1 ? form.defaultLevelList : form.levelList" stripe>
                        <el-table-column prop="levelName" label="等级名称" min-width="180" />
                        <el-table-column label="推广佣金" min-width="180">
                            <template #default="{ row, $index }">
                                <div v-if="form.type == 1">{{ row.rate }}%</div>
                                <el-form-item v-else :prop="`levelList.${$index}.rate`" :rules="rules.required">
                                    <el-input-number
                                        v-model="row.rate"
                                        class="input"
                                        :min="0"
                                        :max="99"
                                        :controls="false"
                                        :precision="2" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="state.distributeInviteSwitchOn" label="邀请佣金" min-width="180">
                            <template #default="{ row, $index }">
                                <div v-if="form.type == 1">{{ row.inviteRate }}%</div>
                                <el-form-item v-else :prop="`levelList.${$index}.inviteRate`" :rules="rules.required">
                                    <el-input-number
                                        v-model="row.inviteRate"
                                        class="input"
                                        :min="0"
                                        :max="99"
                                        :controls="false"
                                        :precision="2" />
                                </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button plain @click="state.show = false">取消</el-button>
                <el-button type="primary" @click="submitHandle(formRef)">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { cloneDeep } from '@/commons/utils';
import request from '@/request';
import { ElMessage } from 'element-plus';
import { nextTick, reactive, ref } from 'vue';

const emit = defineEmits(['close', 'save']);
const state = reactive({
    show: false,
    loading: true,
    saveSuccess: false,
    distributeInviteSwitchOn: false
});
const form = reactive({
    type: 1,
    goodsIds: [],
    defaultLevelList: [],
    levelList: []
});
const formRef = ref(null);
const rules = {
    required: [{ required: true, message: '', trigger: ['blur'] }]
};
/**
 * 弹窗关闭
 */
const onClose = () => {
    if (state.saveSuccess) return;
    emit('close');
};

/**
 * 提交
 */
const submitHandle = async formEl => {
    if (!formEl) return;
    await formEl.validate();
    const params = cloneDeep(form);
    delete params.defaultLevelList;
    if (!state.distributeInviteSwitchOn) {
        params.levelList = params.levelList.map(item => {
            delete item.inviteRate;
            return item;
        });
    }
    await request('addGoodsServ', params);
    state.saveSuccess = true;
    form.type = 1;
    form.goodsIds = [];
    form.defaultLevelList = [];
    form.levelList = [];
    state.show = false;
    ElMessage.success('新增成功');
    emit('save');
};
/**
 * 获取是否开启邀请佣金
 * 获取分销等级列表
 */
const getDetail = async () => {
    const [res1, res2] = await Promise.all([request('getSetConfigServ'), request('queryDistributorLevelListServ')]);
    state.distributeInviteSwitchOn = res1.data?.info.distributeInviteSwitchOn;
    const defaultLevelList = Array.isArray(res2.data.list)
        ? res2.data.list.map(item => {
              return {
                  levelId: item.id,
                  levelName: item.levelName,
                  inviteRate: item.benefitRules.inviteRate,
                  rate: item.benefitRules.rate
              };
          })
        : [];
    form.defaultLevelList = defaultLevelList;
    form.levelList = defaultLevelList.map(item => {
        return {
            levelId: item.levelId,
            levelName: item.levelName,
            inviteRate: 0,
            rate: 0
        };
    });
    await nextTick();
    state.loading = false;
};
/**
 * 打开弹窗
 */
const onOpen = goodsIds => {
    state.saveSuccess = false;
    form.goodsIds = goodsIds;
    state.loading = true;
    getDetail();
    state.show = true;
};

defineExpose({
    onOpen
});
</script>

<style lang="scss" scoped>
.set_dialog {
    .el-form {
        min-height: 250px;
        padding-right: 46px;
        padding-bottom: 53px;
        .el-form-item {
            margin-bottom: 9px;
        }
    }
    .input {
        display: flex;
        align-items: center;
        width: 100px;
        &::after {
            content: '%';
            display: inline-block;
            margin-left: 4px;
        }
    }
}
</style>
